package com.maimang.platform.dsp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maimang.platform.common.utils.DateUtils;
import com.maimang.platform.dsp.constant.AdvertiserApi;
import com.maimang.platform.dsp.entity.AdData;
import com.maimang.platform.dsp.entity.AdvertiserIds;
import com.maimang.platform.dsp.enums.StatType;
import com.maimang.platform.dsp.enums.TimeGranularity;
import com.maimang.platform.dsp.mapper.AdDataMapper;
import com.maimang.platform.dsp.mapper.AdvertiserIdsMapper;
import com.maimang.platform.dsp.service.AccessTokenService;
import com.maimang.platform.dsp.service.AdDataService;
import com.maimang.platform.dsp.utils.ApiService;
import com.maimang.platform.lang.ConvertUtils;
import com.maimang.platform.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname AdDataServiceImpl
 * @description <br>广告主数据服务层实现类</br>
 * @date 2019-11-26 11:23:36
 * @email jintaozhao@qq.com
 */
@Service
public class AdDataServiceImpl implements AdDataService {

	@Autowired
	private AdDataMapper adDataMapper;

	@Autowired
	private AdvertiserIdsMapper advertiserIdsMapper;

	@Autowired
	private ApiService apiService;

	@Autowired
	private AccessTokenService accessTokenService;

	/**
	 * 查询广告主数据信息
	 *
	 * @param pkId 广告主数据ID
	 * @return 广告主数据信息
	 */
	@Override
	public AdData selectAdDataById(Integer pkId) {
		return adDataMapper.selectAdDataById(pkId);
	}

	/**
	 * 查询广告主数据列表
	 *
	 * @param adData 广告主数据信息
	 * @return 广告主数据集合
	 */
	@Override
	public List<AdData> selectAdDataList(AdData adData) {
		return adDataMapper.selectAdDataList(adData);
	}

	/**
	 * 新增广告主数据
	 *
	 * @param adData 广告主数据信息
	 * @return 结果
	 */
	@Override
	public int insertAdData(AdData adData) {
		return adDataMapper.insertAdData(adData);
	}

	/**
	 * 修改广告主数据
	 *
	 * @param adData 广告主数据信息
	 * @return 结果
	 */
	@Override
	public int updateAdData(AdData adData) {
		return adDataMapper.updateAdData(adData);
	}

	/**
	 * 删除广告主数据对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteAdDataByIds(String ids) {
		return adDataMapper.deleteAdDataByIds(ConvertUtils.toStrArray(ids));
	}

	/**
	 * 批量同步广告主数据
	 *
	 * @param ids          广告主id列表
	 * @param recentlyDays 最近多少天的数据，最大30
	 * @return
	 */
	@Override
	public int syncAdDataByIds(String ids, int recentlyDays) {
		if (StringUtils.isEmpty(ids))
			return 0;
		String[] idList = ids.split(",");
		String endDate = DateUtils.getDate();
		String startDate = DateUtils.getBeforeDayString(endDate, recentlyDays);
		for (int i = 0; i < idList.length; i++) {
			String advertiserId = idList[i];
			syncAdData(Long.valueOf(advertiserId), startDate, endDate);
		}

		return idList.length;
	}

	/**
	 * @param advertiserId 代理商广告主id
	 * @param recentlyDays 最近多少天的数据，最大30
	 * @return
	 */
	@Override
	public void syncAdData(Long advertiserId, int recentlyDays) {
		AdvertiserIds ids = new AdvertiserIds();
		ids.setPId(advertiserId);
		List<AdvertiserIds> idsList = advertiserIdsMapper.selectAdvertiserIdsList(ids);
		String today = DateUtils.getToday();
		String startDate = DateUtils.getBeforeDayString(today, recentlyDays);

		double total = idsList.size();

		for (int i = 0; i < total; i++) {
			AdvertiserIds advertiserIds = idsList.get(i);
			// syncData(advertiserIds.getId().toString(), startDate, today);
		}
		// int pageSize = 2000;
		// double totalPage = Math.ceil(total / pageSize);
		// for (int i = 0; i < totalPage; i++) {
		// 	int beginIndex = i * pageSize;
		// 	int endIndex = (int) Math.min((i + 1) * pageSize, total);
		//
		// 	Executors.newCachedThreadPool().execute(() -> {
		// 		List<AdvertiserIds> advertiserIdsList = idsList.subList(beginIndex, endIndex);
		//
		// 		for (int j = 0; j < advertiserIdsList.size(); j++) {
		// 			AdvertiserIds advertiserIds = advertiserIdsList.get(j);
		// 			syncData(advertiserIds.getId().toString(), startDate, today);
		// 			try {
		// 				Thread.sleep(3000);
		// 			} catch (InterruptedException e) {
		// 				e.printStackTrace();
		// 			}
		// 		}
		// 	});
		// }
	}

	/**
	 * @param advertiserId 广告主id
	 * @param startDate    开始日期
	 * @param endDate      结束日期
	 */
	@Override
	public void syncAdData(Long advertiserId, String startDate, String endDate) {
		String[] groupBy = new String[2];
		groupBy[0] = StatType.STAT_GROUP_BY_FIELD_STAT_TIME.getValue();
		groupBy[1] = StatType.STAT_GROUP_BY_FIELD_ID.getValue();

		String timeGranularity = TimeGranularity.STAT_TIME_GRANULARITY_DAILY.getValue();
		String orderField = StringUtils.EMPTY;
		String orderType = "DESC";
		int page = 1;
		int pageSize = 999;
		handleRemoteData(String.valueOf(advertiserId), startDate, endDate, groupBy, timeGranularity, orderField, orderType, page, pageSize);
	}

	/**
	 * 处理远程请求的广告主数据返回结果集
	 *
	 * @param advertiserId    广告主id
	 * @param startDate       开始时间
	 * @param endDate         结束时间
	 * @param groupBy         分组条件
	 * @param timeGranularity 时间粒度
	 * @param page            页码
	 * @param pageSize        页面大小
	 * @param orderField      排序字段
	 * @param orderType       排序类型
	 */
	private void handleRemoteData(String advertiserId, String startDate, String endDate, String[] groupBy, String timeGranularity, String orderField, String orderType, int page, int pageSize) {
		JSONObject result = getAdDataList(advertiserId, startDate, endDate, groupBy, timeGranularity, orderField, orderType, page, pageSize);
		if (result.getIntValue("code") == 0) {
			JSONObject pageInfo = result.getJSONObject("data").getJSONObject("page_info");
			JSONArray dataList = result.getJSONObject("data").getJSONArray("list");
			List<AdData> adDataList = dataList.toJavaList(AdData.class);
			for (int i = 0; i < adDataList.size(); i++) {
				AdData adData = adDataList.get(i);
				adData.setGroupBy(StringUtils.join(groupBy, ","));
				adData.setTimeGranularity(timeGranularity);
				adData.setAdvertiserId(advertiserId);

				// 删除旧数据，减少查询次数
				adDataMapper.deleteAdDataById(adData.getAdId(), adData.getStatDatetime());
				// 重新插入新的数据
				adDataMapper.insertAdData(adData);
			}
			int total_number = pageInfo.getIntValue("total_number");
			pageSize = pageInfo.getIntValue("page_size");
			page = pageInfo.getIntValue("page");
			if (total_number > pageSize * page) {
				try {
					Thread.sleep(2000);
					page++;
					handleRemoteData(advertiserId, startDate, endDate, groupBy, timeGranularity, orderField, orderType, page, pageSize);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}


	/**
	 * 获取广告主基本数据，包括花费、点击量、点击单价等
	 *
	 * @param advertiserId    广告主id
	 * @param startDate       开始日期
	 * @param endDate         结束日期
	 * @param groupBy         分组条件
	 * @param timeGranularity 时间粒度
	 * @param page            页码 默认值: 1,取值范围: ≥ 0
	 * @param pageSize        每页数据量,默认值: 20,取值范围: 1-1000
	 * @param orderField      排序字段
	 * @param orderType       排序类型
	 * @return
	 */
	@Override
	public JSONObject getAdDataList(String advertiserId, String startDate, String endDate, String[] groupBy, String timeGranularity, String orderField, String orderType, int page, int pageSize) {
		String accessToken = accessTokenService.accessToken();
		if (StringUtils.isEmpty(accessToken))
			return null;

		Map params = new HashMap();
		params.put("advertiser_id", advertiserId);
		params.put("start_date", startDate);
		params.put("end_date", endDate);
		if (StringUtils.isNotEmpty(groupBy)) {
			params.put("group_by", groupBy);
		}
		if (StringUtils.isNotEmpty(timeGranularity)) {
			params.put("time_granularity", timeGranularity);
		}
		if (StringUtils.isNotEmpty(orderField)) {
			params.put("order_field", orderField);
		}

		if (StringUtils.isNotEmpty(orderType)) {
			params.put("order_type", orderType);
		}
		if (page >= 0) {
			params.put("page", page);
		}
		if (pageSize >= 1) {
			params.put("page_size", pageSize);
		}
		JSONObject result = apiService.sendGet(AdvertiserApi.REPORT_AD, accessToken, params);

		return result;
	}

}
